import React, {
    PureComponent
} from 'react';

import {
    Text,
    View,
    StyleSheet
} from 'react-native';

import {
    Tip,
    Input,
    Loading,
    AgeRange
} from './../../../components';

import {
    DataItem,
    LocationData
} from './../../../types/types';

import Select from './select';

import OPTIONS from './../../../const/options';
import connection from './../../../utils/connect';

import userAction from './../../../state/actions/user';
import * as userTypes from './../../../state/types/user';

type Value = Array<number> | number;

interface State {
    ageMin: any,
    ageMax: any,
    location: any,
    gender: any,
    distanceMin:any,
    distanceMax:any
}

interface Props {
    user: any,
    userActions: any,
    onFilter: Function,
    onDialogClose: Function
}

@connection([`user`], {
    userActions: userAction
})
class Filter extends PureComponent <Props, State> {
    state = {
        ageMin: 0,
        ageMax: 0,
        distanceMin:0,
        distanceMax:0,
        gender: undefined,
        location: undefined
    }

    static defaultProps = {
        user: {},
        userActions: {},
        onFilter: () => null,
        onDialogClose: () => null
    }

    get userState() {
        const {
            user
        } = this.props;
        return user;
    }

    get loginUser() {
        const {
            loginUser = {}
        } = this.userState;
        return loginUser
    }

    get matchInfo() {
        const {
            matches = {}
        } = this.userState;

        const {
            userId
        } = this.loginUser;

        return matches[userId] || {};
    }

    get userActions() {
        const {
            userActions
        } = this.props;
        return userActions;
    }

    get ageMin() {
        const {
            ageMin
        } = this.state;

        const {
            matchAge = {}
        } = this.matchInfo;
        const {
            min
        } = matchAge;
        return ageMin || min || 18;
    }

    get ageMax() {
        const {
            ageMax
        } = this.state;
        const {
            matchAge = {}
        } = this.matchInfo;
        const {
            max
        } = matchAge;
        return ageMax || max || 100;
    }

    get location(): LocationData {
        const {
            matchLocation = {}
        } = this.matchInfo;

        const {
            location
        } = this.state;

        return location || matchLocation || {};
    }

    get gender() {
        const {
            gender
        } = this.state;

        const {
            matchGender = []
        } = this.matchInfo;

        const _gender = (
            matchGender.map(
                (item: DataItem) => item.id
            )
        )
        return gender || _gender;
    }

    componentDidMount() {
        this.userActions[
            userTypes.getUserMatch
        ]()
    }

    private _onValueChange = (
        value: Value,
        type: string
    ) => {
        const state: any = {
            [type]: value
        }
        this.setState(state)
    }

    private _getIds(array: Array<number>): number {
        return [0, ...array].reduce((a, b) => a + b)
    }

    public onSubmit = async () => {
        const {
            ageMin,
            ageMax,
            gender,
            location
        } = this.state;

        const {
            onFilter
        } = this.props;

        const {
            state,
            country
        } = location || {} as LocationData;


        const {
            id: stateId
        } = state || {}

        const {
            id: countryId
        } = country || {}


        const _para: any = {
            cityId: 0
        }

        if (!!ageMin) {
            _para.minAge = ageMin;
        }

        if (!!ageMax) {
            _para.maxAge = ageMax;
        }

        if (stateId !== undefined) {
            _para.stateId = stateId
        }

        if (countryId !== undefined) {
            _para.countryId = countryId
        }

        if (!!gender) {
            _para.seeking = (
                this._getIds(gender || [])
            )
        }

        Loading.show();

        try {
            await this.userActions[
                userTypes.updateUserMatch
            ](_para);
            onFilter();
            this.onClosePage();
        }
        catch (e) {
            Tip.warm({
                message: e.message
            })
        }

        Loading.close()
    }

    private onOpenAgeRange = async () => {
        const {
            min,
            max
        } = await (
            AgeRange(
                this.ageMin,
                this.ageMax
            )
        )
        this.setState({
            ageMin: min,
            ageMax: max
        })
    }

    get ageValue() {
        return `${this.ageMin} - ${this.ageMax}`;
    }

    private onClosePage = () => {
        const {
            onDialogClose
        } = this.props;
        onDialogClose();
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.content}>
                    <View style={styles.itemRow}>
                        <Text style={styles.title}>
                            Gender
                        </Text>
                        <View style={styles.itemContent}>
                            <Select
                                type="gender"
                                value={this.gender}
                                options={OPTIONS.gender}
                                onChange={this._onValueChange}
                            />
                        </View>
                    </View>
                    <View style={styles.itemRow}>
                        <Text style={styles.title}>
                            Age range
                        </Text>
                        <Input
                            disabled={true}
                            value={this.ageValue}
                            placeholder="Age range"
                            onPress={this.onOpenAgeRange}
                        />
                    </View>
                </View>
            </View>
        )
    }
}

export default Filter;

const styles = StyleSheet.create({
    container: {
        backgroundColor: `#fff`
    },
    content: {
        paddingTop: 20,
        paddingBottom:20,
        paddingHorizontal: 16
    },
    title: {
        fontSize: 18,
        color: `#333`,
        fontWeight:`bold`
    },
    itemRow: {
        marginBottom: 24
    },
    doneText:{
        fontSize:18,
        color:`#fff`,
        fontWeight:`bold`
    },
    doneStyle:{
        height:`100%`,
        paddingLeft:16,
        justifyContent:`center`
    }
}) as any;